<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/12/17
 * Time: 16:00
 */

namespace app\api\controller;


use app\api\model\UUser as UUserModel;//用户
use think\Db;

class My extends Base
{
    /**
     * 我的->用户基本资料
     * @return \think\response\Json
     */
    public function myIntro()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        $userModel = new UUserModel();
        $field = '*';
        $userInfo = $userModel->getUserInfo($params['user_id'], $field);
        return json(['status' => 200, 'msg' => $userInfo]);
    }
    
    /**
     * 我的->用户详细资料
     * @return \think\response\Json
     */
    public function myDetail()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        $userModel = new UUserModel();
        //查询字段
        $field = [
            'user_image',
            'user_username',
            'user_idcard',
            'user_idcard_img',
            'user_zhizhao',
            'user_status',
            'user_shopname',
            'user_type',
            'user_ssq_str',
            'user_address',
            'user_zizhi'
        ];
        $userDetail = $userModel->getUserInfo($params['user_id'], $field)->toArray();
        //身份证照片
        if(!empty($userDetail['user_idcard_img'])) {
            $userDetail['user_idcard_img'] = explode(',', $userDetail['user_idcard_img']);
        } else {
            $userDetail['user_idcard_img'] = [];
        }
        //营业执照
        if(!empty($userDetail['user_zhizhao'])) {
            $userDetail['user_zhizhao'] = explode(',', $userDetail['user_zhizhao']);
        } else {
            $userDetail['user_zhizhao'] = [];
        }
        //资质
        if(!empty($userDetail['user_zizhi'])) {
            $userDetail['user_zizhi'] = explode(',', $userDetail['user_zizhi']);
        } else {
            $userDetail['user_zizhi'] = [];
        }
        return json(['status' => 200, 'msg' => $userDetail]);
    }
    
    /**
     * 编辑用户头像
     * user_image  用户头像
     * @return \think\response\Json
     */
    public function editUserImage()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        //修改头像
        $data = ['user_image' => $params['user_image']];
        $userModel = new UUserModel();
        $result = $userModel->editData($params['user_id'], $data);
        if($result) {
            return json(['status' => 200, 'msg' => '编辑成功']);
        } else {
            return json(['status' => 0, 'msg' => '编辑失败']);
        }
    }
    
    /**
     * 我的->我的收藏
     * page  当前页码
     * @return \think\response\Json
     */
    public function myCollect()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        $page = input('page') ? input('page') : 1;
        $collectLists = Db::table('up_like')
            ->join('up_goods', 'good_id = l_good_id', 'left')
            ->field([
                'good_thumb',
                'good_id',
                'good_name',
                'good_price',
                'y_price'
            ])
            ->page($page, 10)
            ->order('l_time desc')
            ->where('l_user_id', $params['user_id'])
            ->where('good_status', 1)
            ->select();
        return json(['status' => 200, 'msg' => $collectLists]);
    }
    
    /**
     * 我的->收藏->搜索
     * page  当前页码
     * keyword  搜索关键字
     * @return \think\response\Json
     */
    public function searchMyCollect()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        $page = input('page') ? input('page') : 1;
        //关键字模糊搜索
        if(empty($params['keyword'])) {//搜索关键字为空
            $where = [];
        } else {
            $where['good_name'] = ['like', "%" . $params['keyword'] . "%"];
        }
        $where['l_user_id'] = $params['user_id'];//我的
        $where['good_status'] = 1;//未被删除的商品
        $searchLists = Db::table('up_like')
            ->join('up_goods', 'good_id = l_good_id', 'left')
            ->field([
                'good_thumb',
                'good_id',
                'good_name',
                'good_price',
                'y_price'
            ])
            ->page($page, 10)
            ->order('l_time desc')
            ->where($where)
            ->select();
        return json(['status' => 200, 'msg' => $searchLists]);
    }
    
    /**
     * 我的->我的订单
     * page  页码
     * choose  筛选条件
     * @return \think\response\Json
     */
    public function myOrder()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        $this->changeOrderDelByTime($params['user_id']);
        $page = input('page') ? input('page') : 1;//页码
        $where['order_userid'] = $params['user_id'];//我的
        $where['order_del'] = 1;
        //筛选条件 0 全部订单  1 待支付  2 代发货  3 待收货  4 已完成
        if($params['choose'] != 0) {
            $where['order_status'] = $params['choose'];
            $whereC['order_c_status'] = $params['choose'];
        }
        $orderList = [];
        $user_type = Db::table('up_u_user')->where('user_id', $params['user_id'])->value('user_type');
        if($user_type == 1) {//用户
            //全部订单的时候混合展示
            if($params['choose'] == 0) {
                $order = Db::table('up_order')
                    ->field('order_id, order_number, order_status, order_user_pay')
                    ->where($where)
                    ->page($page, 10)
                    ->order('order_time desc')
                    ->select();
                foreach($order as $k => &$v) {
                    //待支付展示总表
                    if($v['order_status'] == 1) {
                        $orderInfoList = Db::table('up_order_info')
                            ->field([
                                'oi_good_thumb',
                                'oi_good_name',
                                'oi_price',
                                'oi_num',
                                'oi_good_id'
                            ])
                            ->where('oi_order_id', $v['order_id'])
                            ->select();
                        $v['sun'] = $orderInfoList;
                        $v['id_type'] = 1;//1  order_id   2  order_c_id
                        $orderList[$k] = $v;
                    } else {
                        $order_child = Db::table('up_order_children')
                            ->field('order_c_id, order_c_number, order_c_status, order_c_user_pay')
                            ->where('order_id', $v['order_id'])
                            ->where('order_c_del', 1)
                            ->select();
                        foreach($order_child as $key => &$vo) {
                            $orderInfoList = Db::table('up_order_info')
                                ->field([
                                    'oi_good_thumb',
                                    'oi_good_name',
                                    'oi_price',
                                    'oi_num',
                                    'oi_good_id'
                                ])
                                ->where('oi_order_chil_id', $vo['order_c_id'])
                                ->select();
                            $vo['sun'] = $orderInfoList;
                            $vo['id_type'] = 2;//1  order_id   2  order_c_id
                            array_push($orderList, $vo);
                        }
                    }
                }
            }
    
            //如果是待支付的订单，则展示总订单,其他状态展示每个被拆分的订单
            if($params['choose'] == 1) {
                $orderList = Db::table('up_order')
                    ->field('order_id, order_number, order_status, order_user_pay')
                    ->where($where)
                    ->page($page, 10)
                    ->order('order_time desc')
                    ->select();
                foreach($orderList as $key => &$vo) {
                    $orderInfoList = Db::table('up_order_info')
                        ->field([
                            'oi_good_thumb',
                            'oi_good_name',
                            'oi_price',
                            'oi_num',
                            'oi_good_id'
                        ])
                        ->where('oi_order_id', $vo['order_id'])
                        ->select();
                    $vo['sun'] = $orderInfoList;
                    $vo['id_type'] = 1;//1  order_id   2  order_c_id
                }
            } else if($params['choose'] == 2 || $params['choose'] == 3 || $params['choose'] == 4) {
                $whereC['order_c_userid'] = $params['user_id'];//我的
                $whereC['order_c_del'] = 1;
                $orderList = Db::table('up_order_children')
                    ->field('order_c_id, order_c_number, order_c_status, order_c_user_pay')
                    ->where($whereC)
                    ->page($page, 10)
                    ->order('order_c_time desc')
                    ->select();
                foreach($orderList as $key => &$vo) {
                    $orderInfoList = Db::table('up_order_info')
                        ->field([
                            'oi_good_thumb',
                            'oi_good_name',
                            'oi_price',
                            'oi_num',
                            'oi_good_id'
                        ])
                        ->where('oi_order_chil_id', $vo['order_c_id'])
                        ->select();
                    $vo['sun'] = $orderInfoList;
                    $vo['id_type'] = 2;//1  order_id   2  order_c_id
                }
            }
        } else {
            $orderList = Db::table('up_order')
                ->field('order_id, order_number, order_status, order_user_pay')
                ->where($where)
                ->page($page, 10)
                ->order('order_time desc')
                ->select();
            //每个订单中的商品
            foreach($orderList as $key => &$vo) {
                $orderInfoList = Db::table('up_order_info')
                    ->field([
                        'oi_good_thumb',
                        'oi_good_name',
                        'oi_price',
                        'oi_num',
                        'oi_good_id'
                    ])
                    ->where('oi_order_id', $vo['order_id'])
                    ->select();
                $vo['sun'] = $orderInfoList;
                $vo['id_type'] = 1;//1  order_id   2  order_c_id
            }
        }
        return json(['status' => 200, 'msg' => $orderList]);
    }
    
    /**
     * 我的->我的收到的订单
     * page  页码
     * choose  筛选条件
     * @return \think\response\Json
     */
    public function receiveOrder()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        $page = input('page') ? input('page') : 1;//页码
        $this->receiveChangeOrderDelByTime($params['user_id']);
        $where['order_c_daili_id'] = $params['user_id'];//属于我的
//        $where['order_c_del'] = 1;
        //筛选条件 0 全部订单  1 待支付  2 代发货  3 待收货  4 已完成
        if($params['choose'] != 0) {
            $where['order_c_status'] = $params['choose'];
        }
        //订单
        $orderList = Db::table('up_order_children')
            ->field('order_c_id, order_c_number, order_c_status, order_c_user_pay')
            ->where($where)
            ->page($page, 10)
            ->order('order_c_time desc')
            ->select();
        //每个订单中的商品
        foreach($orderList as $key => &$vo) {
            $orderInfoList = Db::table('up_order_info')
                ->field([
                    'oi_good_thumb',
                    'oi_good_name',
                    'oi_price',
                    'oi_num',
                    'oi_good_id'
                ])
                ->where('oi_order_chil_id', $vo['order_c_id'])
                ->select();
            $vo['sun'] = $orderInfoList;
            $vo['id_type'] = 2;//1  order_id   2  order_c_id
        }
        return json(['status' => 200, 'msg' => $orderList]);
    }
    
    /**
     * 订单详情
     * id_type   订单ID类型   1  order_id   2  order_c_id
     * order_id|order_c_id  订单ID
     * @return \think\response\Json
     */
    public function orderDetail()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        if($params['id_type'] == 1) {
            //总表订单详情
            $orderDetail = Db::table('up_order')
                ->join('up_u_user', 'user_id = order_userid', 'left')
                ->field(['order_id', 'order_address_name', 'order_address_phone', 'order_address', 'order_number',
                    'order_user_pay', 'order_type', 'order_status', 'order_time', 'user_image'])
                ->where('order_id', $params['order_id'])
                ->find();
            //订单下的商品
            $orderGoods = Db::table('up_order_info')
                ->field([
                    'oi_good_thumb',
                    'oi_good_name',
                    'oi_price',
                    'oi_num',
                    'oi_good_id'
                ])
                ->where('oi_order_id', $params['order_id'])
                ->select();
        } else {
            //分表订单详情
            $orderDetail = Db::table('up_order_children')
                ->alias('uoc')
                ->join('up_u_user', 'user_id = order_c_userid', 'left')
                ->join('up_order uo', 'uoc.order_id = uo.order_id', 'left')
                ->field(['order_c_id', 'order_c_address_name', 'order_c_address_phone', 'order_c_address', 'order_c_number',
                    'order_c_user_pay', 'order_type', 'order_c_status', 'order_c_time', 'user_image'])
                ->where('order_c_id', $params['order_c_id'])
                ->find();
            //订单下的商品
            $orderGoods = Db::table('up_order_info')
                ->field([
                    'oi_good_thumb',
                    'oi_good_name',
                    'oi_price',
                    'oi_num',
                    'oi_good_id'
                ])
                ->where('oi_order_chil_id', $params['order_c_id'])
                ->select();
        }
        
        $orderDetail['sun'] = $orderGoods;
        return json(['status' => 200, 'msg' => $orderDetail]);
    }
    
    /**
     * 删除/取消订单
     * order_id  订单ID
     * type  1 取消订单  2 删除订单
     * id_type 1总订单  2 分订单
     * @return \think\response\Json
     */
    public function delOrder()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        if($params['id_type'] == 1){
            $orderInfo = Db::table('up_order')->find($params['order_id']);
            if(!$orderInfo) {
                return json(['status' => 0, 'msg' => '订单不存在']);
            }
        }else{
            $orderInfo = Db::table('up_order_children')->find($params['order_c_id']);
            if(!$orderInfo) {
                return json(['status' => 0, 'msg' => '订单不存在']);
            }
        }
        $userInfo = Db::table('up_u_user')->where('user_id', $params['user_id'])->find();
        
        Db::startTrans();
        try {
            if($params['type'] == 1){//取消订单
                //取消总表订单
                Db::table('up_order')->where('order_id', $params['order_id'])->delete();
                //如果是用户删除，则需要修改分表中的对应状态
                if($userInfo['user_type'] == 1){
                    //修改分表记录的状态
                    Db::table('up_order_children')->where('order_id', $params['order_id'])->delete();
                }
                
                //删除订单下的商品
//            Db::table('up_order_info')->where('oi_order_id', $params['order_id'])->delete();
                //插入消息表
                $data = [
                    'n_title' => '商城订单取消',//标题
                    'n_content' => '您编号为' . $orderInfo['order_number'] . '的订单已取消',//内容
                    'n_type' => 2,//系统消息
                    'n_user_id' => $params['user_id'],//用户ID
                    'n_read' => 0,//已读
                    'n_delete' => 0,//已删除
                    'n_time' => date('Y-m-d H:i:s')//发布时间
                ];
                Db::table('up_notice')->insert($data);
            }else{
                if($params['id_type'] == 2){//用户删除订单
                    //订单信息
                    $order_c_info = Db::table('up_order_children')->where('order_c_id', $params['order_c_id'])->find();
                    //删除分表订单
                    Db::table('up_order_children')->where('order_c_id', $params['order_c_id'])->setField('order_c_del', 2);
                    //是否所有分表订单都删除，如果是，则改变总表中的记录
                    $order_count = Db::table('up_order_children')->where('order_id', $order_c_info['order_id'])->count();
                    $order_count_affirm = Db::table('up_order_children')
                        ->where('order_id', $order_c_info['order_id'])
                        ->where('order_c_del', 2)
                        ->count();
                    if($order_count == $order_count_affirm) {
                        Db::table('up_order')->where('order_id', $order_c_info['order_id'])->setField('order_del', 2);
                    }
                }else{
                    Db::table('up_order')->where('order_id', $params['order_id'])->setField('order_del', 2);
                }
            }
            
            
            Db::commit();
            $result = 1;
        } catch(\Exception $e) {
            Db::rollback();
            $result = 0;
        }
        if($result == 1) {
            return json(['status' => 200, 'msg' => '操作成功']);
        } else {
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 用户确认收货
     * order_c_id  分表订单ID
     * @return \think\response\Json
     */
    public function userAffirmOrder()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        
        Db::startTrans();
        try {
            //修改分表订单状态
            $sureUpdateF = [
                'order_c_status' => 4,//已完成
                'order_c_suretime' => date('Y-m-d H:i:s'),//订单确认时间
            ];
            Db::table('up_order_children')->where('order_c_id', $params['order_c_id'])->update($sureUpdateF);
    
            //订单信息
            $order_c_info = Db::table('up_order_children')->where('order_c_id', $params['order_c_id'])->find();
            
            //插入消息表
            $data = [
                'n_title' => '商城订单完成',//标题
                'n_content' => '您编号为' . $order_c_info['order_c_number'] . '的订单已确认收货',//内容
                'n_type' => 2,//个人消息
                'n_user_id' => $params['user_id'],//用户ID
                'n_read' => 0,//未读
                'n_delete' => 0,//未删除
                'n_time' => date('Y-m-d H:i:s')//发布时间
            ];
            Db::table('up_notice')->insert($data);
            
            //是否所有分表订单都确认收货，如果是，则改变总表中的记录
            $order_count = Db::table('up_order_children')->where('order_id', $order_c_info['order_id'])->count();
            $order_count_affirm = Db::table('up_order_children')
                ->where('order_id', $order_c_info['order_id'])
                ->where('order_c_status', 4)
                ->count();
            if($order_count == $order_count_affirm) {
                //修改订单状态
                $sureUpdate = [
                    'order_status' => 4,//已完成
                    'order_suretime' => date('Y-m-d H:i:s'),//订单确认时间
                ];
                Db::table('up_order')->where('order_id', $order_c_info['order_id'])->update($sureUpdate);
            }
            
            Db::commit();
            $result = 1;
        } catch(\Exception $e) {
            Db::rollback();
            $result = 0;
        }
        if($result == 1) {
            try{
                $user_id = (string)$order_c_info['order_c_daili_id'];
                $str = '您编号为' . $order_c_info['order_c_number'] . '的客户订单已确认收货';
                $this->Jpush(1, $user_id, $str, ['type' => '']);
            }catch(\Exception $e){

            }
            return json(['status' => 200, 'msg' => '操作成功']);
        } else {
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 运营确认收货
     * order_id  分表订单ID
     * @return \think\response\Json
     */
    public function operateAffirmOrder()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        
        Db::startTrans();
        try {
            //修改分表订单状态
            $sureUpdate = [
                'order_status' => 4,//已完成
                'order_suretime' => date('Y-m-d H:i:s'),//订单确认时间
            ];
            Db::table('up_order')->where('order_id', $params['order_id'])->update($sureUpdate);
    
            //订单信息
            $order_info = Db::table('up_order')->where('order_id', $params['order_id'])->find();
            
            //插入消息表
            $data = [
                'n_title' => '商城订单完成',//标题
                'n_content' => '您编号为' . $order_info['order_number'] . '的订单已确认收货',//内容
                'n_type' => 2,//个人消息
                'n_user_id' => $order_info['order_userid'],//该订单的用户ID
                'n_read' => 0,//未读
                'n_delete' => 0,//未删除
                'n_time' => date('Y-m-d H:i:s')//发布时间
            ];
            Db::table('up_notice')->insert($data);
            
            Db::commit();
            $result = 1;
        } catch(\Exception $e) {
            Db::rollback();
            $result = 0;
        }
        if($result == 1) {
            return json(['status' => 200, 'msg' => '操作成功']);
        } else {
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 运营确认发货
     * order_c_id  确认发货的订单ID
     * @return \think\response\Json
     */
    public function sureSendOut()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        Db::startTrans();
        try {
            //修改订单状态
            Db::table('up_order_children')->where('order_c_id', $params['order_c_id'])->setField('order_c_status', 3);
            
            //插入消息表
            $orderInfo = Db::table('up_order_children')->where('order_c_id', $params['order_c_id'])->find();
            $data = [
                'n_title' => '商城订单已发货',//标题
                'n_content' => '您编号为' . $orderInfo['order_c_number'] . '的订单已发货',//内容
                'n_type' => 2,//个人消息
                'n_user_id' => $orderInfo['order_c_userid'],//该订单的用户ID
                'n_read' => 0,//未读
                'n_delete' => 0,//未删除
                'n_time' => date('Y-m-d H:i:s')//发布时间
            ];
            Db::table('up_notice')->insert($data);
    
            //是否所有分表订单都确认收货，如果是，则改变总表中的记录
            $order_count = Db::table('up_order_children')->where('order_id', $orderInfo['order_id'])->count();
            $order_count_affirm = Db::table('up_order_children')
                ->where('order_id', $orderInfo['order_id'])
                ->where('order_c_status', 3)
                ->count();
            if($order_count == $order_count_affirm) {
                Db::table('up_order')->where('order_id', $orderInfo['order_id'])->setField('order_status', 3);
            }
            
            Db::commit();
            $result = 1;
        } catch(\Exception $e) {
            Db::rollback();
            $result = 0;
        }
        if($result == 1) {
            try{
                $user_id = (string)$data['n_user_id'];
                $this->Jpush(1, $user_id, $data['n_content'], ['type' => '']);
            }catch(\Exception $e){
                
            }
            return json(['status' => 200, 'msg' => '操作成功']);
        } else {
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 验证绑定的手机号
     * phone  用户输入的手机号
     * @return \think\response\Json
     */
    public function verifyPhone()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        $startTime = date('Y-m-d 00:00:00');//今日开始时间
        $endTime = date('Y-m-d 23:59:59');//今日结束时间
        //当天输入错误的次数
        $errorNum = Db::table('up_phone_error')
            ->whereTime('error_time', 'between', [$startTime, $endTime])
            ->where('error_user_id', $params['user_id'])
            ->count();
        if($errorNum == 5) {
            return json(['status' => 0, 'msg' => '今日已输入错误5次，请明天再输入']);
        }
        //判断输入的手机号是否正确,如果错误，则插入到数据库表中
        $phone = Db::table('up_u_user')->where('user_id', $params['user_id'])->value('user_phone');
        if(trim($params['phone'], ' ') != $phone) {//手机号错误
            $data = [
                'error_user_id' => $params['user_id'],//用户ID
                'error_user_phone' => $params['phone'],//错误的手机号
                'error_time' => date('Y-m-d H:i:s'),
            ];
            Db::table('up_phone_error')->insert($data);
            return json(['status' => 0, 'msg' => '输入的手机号与绑定手机号不一致']);
        }
        return json(['status' => 200, 'msg' => '']);
    }
    
    /**
     * 当前绑定的手机号
     * @return \think\response\Json
     */
    public function nowBandPhone()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        $phone = Db::table('up_u_user')->where('user_id', $params['user_id'])->value('user_phone');
        return json(['status' => 200, 'msg' => $phone]);
    }
    
    /**
     * 我的->我的钱包->我的余额
     * @return \think\response\Json
     */
    public function myBalance()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        $balance = Db::table('up_u_user')->where('user_id', $params['user_id'])->value('user_money');
        return json(['status' => 200, 'msg' => $balance]);
    }
    
    /**
     * 我的->我的钱包->我的账单->收入/支出
     * deal_type  1 收入  2 支出
     * page  当前页码
     * @return \think\response\Json
     */
    public function myDeal()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        if($params['deal_type'] == 1) {//收入
            $where['ji_type'] = 1;
        } else {//支出
            $where['ji_type'] = 2;
        }
        $where['ji_user_id'] = $params['user_id'];
        $where['ji_status'] = 2;
        $page = input('page') ? input('page') : 1;
        $dealList = Db::table('up_jilu')
            ->field('ji_id, ji_title, ji_type, ji_from, ji_money, ji_time')
            ->where($where)
            ->page($page, 10)
            ->order('ji_time desc')
            ->select();
        return json(['status' => 200, 'msg' => $dealList]);
    }
    
    /**
     * 我的->我的钱包->我的账单->收入/支出
     * ji_id  交易记录ID
     * @return \think\response\Json
     */
    public function dealDetail()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        $info = Db::table('up_jilu')
            ->where('ji_id', $params['ji_id'])
            ->field('ji_id, ji_num, ji_title, ji_type, ji_from, ji_money, ji_time')
            ->find();
        return json(['status' => 200, 'msg' => $info]);
    }
    
    /**
     * 我的->消息->系统消息
     * @return \think\response\Json
     */
    public function systemNotice()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        $noticeList = $this->selectUnreadNotice(1, $params);//未读消息
        $selectAllNotice = $this->selectAllNotice(1, $params, 1);//所有消息
        if(empty($selectAllNotice)) {
            $title = '';
            $time = '';
        } else {
            $title = $selectAllNotice[0]['n_title'];
            $time = $selectAllNotice[0]['n_time'];
        }
        //数量
        $count = count($noticeList);
        if($count >= 99) {
            $count = 99;
        }
        $data = [
            'num' => $count,//未读消息数量
            'title' => $title,//最后一条未读消息的标题
            'time' => $time,//最后一条未读消息的时间
        ];
        return json(['status' => 200, 'msg' => $data]);
    }
    
    /**
     * 我的->消息->交易消息
     * @return \think\response\Json
     */
    public function dealNotice()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        
        $noticeList = $this->selectUnreadNotice(2, $params);//未读消息
        $selectAllNotice = $this->selectAllNotice(2, $params, 1);//所有消息
        if(empty($selectAllNotice)) {
            $title = '';
            $time = '';
        } else {
            $title = $selectAllNotice[0]['n_title'];
            $time = $selectAllNotice[0]['n_time'];
        }
        //数量
        $count = count($noticeList);
        if($count >= 99) {
            $count = 99;
        }
        $data = [
            'num' => $count,//未读消息数量
            'title' => $title,//最后一条未读消息的标题
            'time' => $time,//最后一条未读消息的时间
        ];
        return json(['status' => 200, 'msg' => $data]);
    }
    
    /**
     * @return \think\response\Json
     * 所有未读消息总数量，用于提示‘我的’->消息提示
     */
    public function noticeNum(){
        $params = input('param.');
        $noticeList1 = $this->selectUnreadNotice(1, $params);//未读系统消息
        $noticeList2 = $this->selectUnreadNotice(2, $params);//未读交易消息
        $count1 = count($noticeList1);
        $count2 = count($noticeList2);
        $count = $count1 + $count2;
        return json(['status' => 200, 'msg' => $count]);
    }
    
    /**
     * 系统消息列表
     * page  页码
     * @return \think\response\Json
     */
    public function systemNoticeList()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        $page = input('page') ? input('page') : 1;
        
        $noticeList = $this->selectAllNotice(1, $params, $page);
        //已读、未读
        foreach($noticeList as $key => &$val) {
            $n_read = trim($val['n_read'], ',');
            $n_read_arr = explode(',', $n_read);
            if(in_array($params['user_id'], $n_read_arr)) {
                $val['n_read'] = 1;//已读
            } else {
                $val['n_read'] = 2;//未读
            }
            //时间格式  年-月-日
            $val['n_time'] = date('Y-m-d', strtotime($val['n_time']));
        }
        return json(['status' => 200, 'msg' => $noticeList]);
    }
    
    /**
     * 交易消息列表
     * page  页码
     * @return \think\response\Json
     */
    public function dealNoticeList()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        $page = input('page') ? input('page') : 1;
        
        $noticeList = $this->selectAllNotice(2, $params, $page);
        //时间格式  年-月-日
        foreach($noticeList as $key => &$val) {
            $val['n_time'] = date('Y-m-d', strtotime($val['n_time']));
        }
        return json(['status' => 200, 'msg' => $noticeList]);
    }
    
    /**
     * 消息详情
     * n_id  消息ID
     * @return \think\response\Json
     */
    public function noticeDetail()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        $noticeInfo = Db::table('up_notice')->where('n_id', $params['n_id'])->find();
        //消息不存在
        if(!$noticeInfo) {
            return json(['status' => 0, 'msg' => '消息不存在']);
        }
        //如果是未读消息，需要标记为已读
        if($noticeInfo['n_type'] == 1) {//系统消息
            $read = trim($noticeInfo['n_read'], ',');
            $read_arr = explode(',', $read);
            if(!in_array($params['user_id'], $read_arr)) {//未读
                $n_read = $noticeInfo['n_read'] . $params['user_id'] . ',';
                //更新已读字段
                Db::table('up_notice')->where('n_id', $params['n_id'])->update(['n_read' => $n_read]);
            }
        } else {//交易消息
            if($noticeInfo['n_read'] == 0) {//未读
                $n_read = 1;
                //更新已读字段
                Db::table('up_notice')->where('n_id', $params['n_id'])->update(['n_read' => $n_read]);
                //todo:如果需要跳转到交易订单详情，在此处处理
                //$onticeInfo
            }
        }
        return json(['status' => 200, 'msg' => $noticeInfo]);
    }
    
    /**
     * 删除消息
     * n_id  消息ID
     * @return \think\response\Json
     */
    public function delNotice()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        $noticeInfo = Db::table('up_notice')->where('n_id', $params['n_id'])->find();
        //消息不存在
        if(!$noticeInfo) {
            return json(['status' => 0, 'msg' => '消息不存在']);
        }
        if($noticeInfo['n_type'] == 1) {//系统消息
            $n_delete = $noticeInfo['n_delete'] . $params['user_id'] . ',';
            $result = Db::table('up_notice')->where('n_id', $params['n_id'])->update(['n_delete' => $n_delete]);
        } else {//交易消息
            $result = Db::table('up_notice')->where('n_id', $params['n_id'])->delete();
        }
        if($result) {
            return json(['status' => 200, 'msg' => '删除成功']);
        } else {
            return json(['status' => 0, 'msg' => '删除失败']);
        }
    }
    
    /**
     * 清空列表
     * notice_type  需要清空的消息类型  1 系统消息  2 交易消息
     * @return \think\response\Json
     */
    public function emptyNotice()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status' => 301, 'msg' => 'Token失效！请重新登录！']);
        }
        if($params['notice_type'] == 1) {//系统消息
            $user_id = ',' . $params['user_id'] . ',';
            $where['n_delete'] = ['notlike', "%" . $user_id . "%"];//未删除
            $where['n_type'] = 1;//系统消息
            
            $noticeList = Db::table('up_notice')
                ->field('n_id, n_read, n_delete')
                ->where($where)
                ->select();
            //循环修改已读、已删除字段，清空列表
            Db::startTrans();
            try {
                foreach($noticeList as $key => &$val) {
                    $data = [
                        'n_read' => $val['n_read'] . $params['user_id'] . ',',//已读
                        'n_delete' => $val['n_delete'] . $params['user_id'] . ',',//已删除
                    ];
                    Db::table('up_notice')->where('n_id', $val['n_id'])->update($data);
                }
                Db::commit();
                $result = 1;
            } catch(\Exception $e) {
                Db::rollback();
                $result = 2;
            }
        } else {
            $back = Db::table('up_notice')->where('n_user_id', $params['user_id'])->delete();
            if($back) {
                $result = 1;
            } else {
                $result = 2;
            }
        }
        if($result == 1) {
            return json(['status' => 200, 'msg' => '清空列表成功']);
        } else {
            return json(['status' => 0, 'msg' => '清空列表失败']);
        }
    }
    
    /**
     * 获取未读消息列表
     * @param $notice_type
     * @param $params
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function selectUnreadNotice($notice_type, $params)
    {
        if($notice_type == 1) {//未读系统消息
            $user_id = ',' . $params['user_id'] . ',';
            $where['n_read'] = ['notlike', "%" . $user_id . "%"];//未读
            $where['n_delete'] = ['notlike', "%" . $user_id . "%"];//未删除
            $where['n_type'] = 1;//系统消息
        } else {
            $where['n_user_id'] = $params['user_id'];//所有消息
            $where['n_read'] = 0;//未读
            $where['n_delete'] = 0;//未删除
            $where['n_type'] = 2;//交易消息
        }
        $noticeList = Db::table('up_notice')
            ->field('n_title, n_time')
            ->where($where)
            ->order('n_time desc')
            ->select();
        return $noticeList;
    }
    
    /**
     * 获取所有消息列表
     * @param $notice_type
     * @param $params
     * @param $page
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function selectAllNotice($notice_type, $params, $page)
    {
        if($notice_type == 1) {//所有系统消息
            $user_id = ',' . $params['user_id'] . ',';
            $where['n_delete'] = ['notlike', "%" . $user_id . "%"];//未删除
            $where['n_type'] = 1;//系统消息
        } else {//所有交易消息
            $where['n_user_id'] = $params['user_id'];//所有消息
            $where['n_delete'] = 0;//未删除
            $where['n_type'] = 2;//交易消息
        }
        $noticeList = Db::table('up_notice')
            ->field('n_id, n_title, n_time, n_content, n_read')
            ->where($where)
            ->page($page, 10)
            ->order('n_time desc')
            ->select();
        return $noticeList;
    }
    
    /**
     * 修改超过半小时未支付的订单为已删除状态--我的订单
     * @param $user_id
     */
    public function changeOrderDelByTime($user_id)
    {
        $time = date('Y-m-d H:i:s', strtotime('-30 minute'));
        $whereDel['order_time'] = ['<=', $time];//下单时间为半个小时之前的
        $whereDel['order_userid'] = $user_id;//我的
        $whereDel['order_del'] = 1;
        $whereDel['order_status'] = 1;//未支付
        $del_list = Db::table('up_order')
            ->field('order_number, order_userid, order_id')
            ->where($whereDel)
            ->select();
        //将订单状态改为已删除
        Db::startTrans();
        try {
            if($del_list) {
                foreach($del_list as $k => $v) {
                    //删除分表中的记录
                    $order_ch = Db::table('up_order_children')
                        ->where('order_id', $v['order_id'])
                        ->select();
                    if($order_ch) {
                        Db::table('up_order_children')
                            ->where('order_id', $v['order_id'])
                            ->setField('order_c_del', 2);
                    }
                    //删除总表中的记录
                    Db::table('up_order')
                        ->where('order_id', $v['order_id'])
                        ->setField('order_del', 2);
                }
            }
            Db::commit();
        } catch(\Exception $e) {
            Db::rollback();
        }
        
    }
    
    /**
     * 修改超过半小时未支付的订单为已删除状态--我收到的订单
     * @param $user_id
     */
    public function receiveChangeOrderDelByTime($user_id)
    {
//        $userInfo = Db::table('up_u_user')->where('user_id', $user_id)->find();
        //获取我所在城市的所有用户ID
//        $user_ids = Db::table('up_u_user')
//            ->where('user_shi', $userInfo['user_shi'])
//            ->where('user_type', 1)
//            ->column('user_id');
        
        $time = date('Y-m-d H:i:s', strtotime('-30 minute'));
        $whereDel['order_time'] = ['<=', $time];//下单时间为半个小时之前的
        $whereDel['order_daili_id'] = $user_id;//我的
        $whereDel['order_del'] = 1;
        $whereDel['order_status'] = 1;//未支付
        $del_list = Db::table('up_order')
            ->field('order_number, order_userid, order_id')
            ->where($whereDel)
            ->select();
        //将订单状态改为已删除
        Db::startTrans();
        try {
            if($del_list) {
                foreach($del_list as $k => $v) {
                    //分表中的记录状态改为删除
                    $order_ch = Db::table('up_order_children')
                        ->where('order_id', $v['order_id'])
                        ->select();
                    if($order_ch) {
                        Db::table('up_order_children')
                            ->where('order_id', $v['order_id'])
                            ->setField('order_c_del', 2);
                    }
                    //总表中的记录状态改为删除
                    Db::table('up_order')
                        ->where('order_id', $v['order_id'])
                        ->setField('order_del', 2);
                }
            }
            Db::commit();
        } catch(\Exception $e) {
            Db::rollback();
        }
        
    }
}